/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

const (
	LOCALE_LIST_FILE = "/usr/share/i18n/SUPPORTED"
)

func getLocaleList() ([]string, bool) {
	contents, err := ioutil.ReadFile(LOCALE_LIST_FILE)
	if err != nil {
		fmt.Printf("ReadFile '%s' Failed: %v\n",
			LOCALE_LIST_FILE, err)
		return []string{}, false
	}

	lines := strings.Split(string(contents), "\n")
	ret := []string{}
	for _, line := range lines {
		if ok, _ := regexp.MatchString(`^#`, line); ok {
			continue
		}

		if ok, _ := regexp.MatchString(`UTF-8$`, line); ok {
			strs := strings.Split(line, " ")
			ret = append(ret, strs[0])
		}
	}

	return ret, true
}

func getDescById(name string) (string, bool) {
	contents, err := ioutil.ReadFile(name)
	if err != nil {
		fmt.Printf("ReadFile '%s' failed: %v\n", name, err)
		return "", false
	}

	lines := strings.Split(string(contents), "\n")
	for _, line := range lines {
		if ok, _ := regexp.MatchString(`^title`, line); ok {
			strs := strings.Split(line, "\"")
			if len(strs) == 3 {
				return strs[1], true
			}
		}
	}

	return "", false
}

func getLocalDescList() map[string]string {
	baseName := "/usr/share/i18n/locales/"
	fp, err := os.Open(baseName)
	if err != nil {
		fmt.Printf("Open '%s' failed: %v\n", baseName, err)
		return nil
	}
	defer fp.Close()

	names, _ := fp.Readdir(0)
	idDescMap := make(map[string]string)
	for _, name := range names {
		if name.Mode().IsRegular() {
			if desc, ok := getDescById(baseName + name.Name()); ok {
				idDescMap[name.Name()] = desc
			}
		}
	}

	return idDescMap
}

func main() {
	if ret, ok := getLocaleList(); ok {
		for _, v := range ret {
			fmt.Println(v)
		}
	}

	/*
		ret := getLocalDescList()
		for k, v := range ret {
			fmt.Printf("%s: \t%s\n", k, v)
		}
	*/

	return
}
